import React, { useEffect } from 'react'
import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
// 路由守卫 对跳转逻辑进行判断 
interface state{
    userReducer:{
        token:string|null
    }
}
interface PrivateRouterProps{
    allowed:boolean
    redirectTo:string
    children:React.ReactNode//react的一个节点
}
//通过allowd判断该页面是否需要登
export default function PrivateRouter({allowed,redirectTo,children}:PrivateRouterProps) {
    // 正确访问token state的路径是tokenReducer.token
    const {token} = useSelector((state:state)=>state.userReducer)
    const isLogin = !!token // 使用双感叹号进行布尔值转换
    const navigator=useNavigate()
    useEffect(()=>{
        if(allowed!==isLogin){
            //未登录 或是 访问页面不需要登录
            navigator(redirectTo,{replace:true})
        }
    },[allowed,isLogin,redirectTo])
    return allowed===isLogin?children:null
}
